package org.example.managere.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.example.managere.dto.FMEAFMESDto;
import org.example.managere.service.FMEAFMESService;
import org.example.managere.util.CsvImportUtil;
import org.example.managere.util.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 数据导入导出控制器
 */
@RestController
@RequestMapping("/api/data")
public class DataExportImportController {

    private final FMEAFMESService fmeafmesService;

    @Autowired
    public DataExportImportController(FMEAFMESService fmeafmesService) {
        this.fmeafmesService = fmeafmesService;
    }

    /**
     * 导出失效模式分析数据为Excel
     */
    @GetMapping("/export/fmeafmes/excel")
    public void exportFMEAFMESToExcel(HttpServletResponse response) throws IOException {
        List<FMEAFMESDto> dataList = fmeafmesService.getAllFMEAFMES();
        
        // 定义表头
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put("id", "ID");
        headers.put("name", "产品名称");
        headers.put("initialConventionLevel", "初始约定等级");
        headers.put("conventionLevel", "约定等级");
        headers.put("system", "系统");
        headers.put("subsystem", "子系统");
        headers.put("fMode", "失效模式");
        headers.put("fCause", "失效原因");
        headers.put("flightPhase", "飞行阶段");
        headers.put("fEffects", "失效影响");
        headers.put("singleFailureRate", "单一故障率");
        headers.put("fmFailureRate", "故障率");
        headers.put("hazardRating", "危害等级");
        headers.put("detectionMethod", "检测方法");
        headers.put("correctiveAction", "纠正措施");
        
        // 生成Excel文件
        byte[] excelBytes = ExcelExportUtil.exportToExcel(headers, dataList, "失效模式分析数据");
        
        // 设置响应头
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String fileName = "FMEAFMES_" + dateFormat.format(new Date()) + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
        response.setContentLength(excelBytes.length);
        
        // 写入响应
        response.getOutputStream().write(excelBytes);
        response.getOutputStream().flush();
    }
    
    /**
     * 导入失效模式分析数据（从CSV文件）
     */
    @PostMapping(value = "/import/fmeafmes/csv", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> importFMEAFMESFromCsv(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty() || !file.getOriginalFilename().endsWith(".csv")) {
                return ResponseEntity.badRequest().body("请上传有效的CSV文件");
            }
            
            List<FMEAFMESDto> importedData = CsvImportUtil.importFromCsv(file, FMEAFMESDto.class);
            List<FMEAFMESDto> savedData = new ArrayList<>();
            
            for (FMEAFMESDto item : importedData) {
                // 移除ID，避免更新现有记录
                item.setId(null);
                savedData.add(fmeafmesService.createFMEAFMES(item));
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "成功导入 " + savedData.size() + " 条失效模式分析数据");
            response.put("importedCount", savedData.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("导入失败: " + e.getMessage());
        }
    }
} 